// stores/modules/device.js - 智能体(设备)模块状态管理
import { defineStore } from 'pinia'
import api from '@/api/modules'

export const useDeviceStore = defineStore('device', {
  state: () => ({
    privateDevices: [],
    publicDevices: [],
    collectedDevices: [],
    currentDeviceId: null
  }),
  
  getters: {
    getCurrentDevice: (state) => {
      if (!state.currentDeviceId) return null
      
      // 首先在私有设备中查找
      let device = state.privateDevices.find(d => d.id === state.currentDeviceId)
      
      // 如果没找到，在公共设备中查找
      if (!device) {
        device = state.publicDevices.find(d => d.id === state.currentDeviceId)
      }
      
      // 如果仍然没找到，在收藏设备中查找
      if (!device) {
        device = state.collectedDevices.find(d => d.id === state.currentDeviceId)
      }
      
      return device
    }
  },
  
  actions: {
    // 设置当前设备ID
    setCurrentDeviceId(id) {
      this.currentDeviceId = id
    },
    
    // 加载私有设备列表
    async loadPrivateDevices() {
      try {
        console.log('开始加载私有设备列表')
        const res = await api.device.getPrivateDevices()
        console.log('私有设备列表响应:', res)
        if (res.code === 200) {
          // 确保创建者名称正确
          // 检查res.data是否是对象而不是数组
          let devices = [];
          if (res.data) {
            // 如果data是对象且包含records字段（分页数据结构）
            if (res.data.records) {
              devices = res.data.records;
            } 
            // 如果data本身就是数组
            else if (Array.isArray(res.data)) {
              devices = res.data;
            }
            // 如果data是单个对象，将其转换为数组
            else if (typeof res.data === 'object') {
              devices = [res.data];
            }
          }
          
          // 确保devices是数组后再使用forEach
          if (Array.isArray(devices)) {
            devices.forEach(device => {
              if (!device.creatorName && device.userId === null) {
                device.creatorName = '系统'
              } else if (!device.creatorName && device.userId) {
                device.creatorName = `用户${device.userId}`
              }
            })
          }
          this.privateDevices = devices
        }
        return res
      } catch (error) {
        console.error('加载私有设备列表失败:', error)
        throw error
      }
    },
    
    // 加载公共设备列表
    async loadPublicDevices(params) {
      try {
        console.log('开始加载公共设备列表, 参数:', params)
        const res = await api.device.getPublicDevices(params)
        console.log('公共设备列表响应:', res)
        
        if (res.code === 200 && res.data && res.data.records) {
          // 如果是第一页，则替换数组，否则追加
          const records = res.data.records.map(device => {
            // 确保有创建者名称
            if (!device.creatorName && device.userId === null) {
              device.creatorName = '系统'
            } else if (!device.creatorName) {
              device.creatorName = `用户${device.userId || ''}`
            }
            
            // 确保收藏状态字段一致
            device.isCollected = device.collected || device.isCollected || false
            device.collected = device.isCollected
            
            return device
          })
          
          if (params.current === 1) {
            this.publicDevices = records
          } else {
            // 过滤掉重复的记录
            const newRecords = records.filter(record => 
              !this.publicDevices.some(existing => existing.id === record.id)
            )
            this.publicDevices = [...this.publicDevices, ...newRecords]
          }
        }
        return res
      } catch (error) {
        console.error('加载公共设备列表失败:', error)
        throw error
      }
    },
    
    // 加载收藏设备列表
    async loadCollectedDevices() {
      try {
        console.log('开始加载收藏设备列表')
        const res = await api.device.getCollectedDevices()
        console.log('收藏设备列表响应:', res)
        
        if (res.code === 200 && res.data) {
          // 检查是否有records字段（分页结构）
          let devices = [];
          if (res.data.records) {
            devices = res.data.records;
          } else {
            // 如果没有records字段（可能是旧格式），直接使用data
            devices = Array.isArray(res.data) ? res.data : [];
          }
          
          // 确保有创建者名称
          devices.forEach(device => {
            if (!device.creatorName && device.userId === null) {
              device.creatorName = '系统'
            } else if (!device.creatorName) {
              device.creatorName = `用户${device.userId || ''}`
            }
            
            // 确保收藏状态字段一致
            device.isCollected = true
            device.collected = true
          })
          
          this.collectedDevices = devices;
        } else {
          console.warn('加载收藏列表返回非200状态或数据为空:', res)
          this.collectedDevices = [];
        }
        
        return {
          code: 200,
          data: this.collectedDevices,
          success: true
        }
      } catch (error) {
        console.error('加载收藏设备列表失败:', error)
        this.collectedDevices = [];
        return {
          code: 200,
          data: [],
          success: true
        }
      }
    },
    
    // 创建设备
    async createDevice(data) {
      try {
        const res = await api.device.createDevice(data)
        // 创建成功后刷新私有设备列表
        await this.loadPrivateDevices()
        return res
      } catch (error) {
        throw error
      }
    },
    
    // 更新设备
    async updateDevice(id, data) {
      try {
        const res = await api.device.updateDevice(id, data)
        // 更新成功后刷新私有设备列表
        await this.loadPrivateDevices()
        return res
      } catch (error) {
        throw error
      }
    },
    
    // 删除设备
    async deleteDevice(id) {
      try {
        const res = await api.device.deleteDevice(id)
        // 删除成功后刷新私有设备列表
        await this.loadPrivateDevices()
        return res
      } catch (error) {
        throw error
      }
    },
    
    // 收藏设备
    async collectDevice(id) {
      try {
        console.log('开始收藏设备:', id)
        const res = await api.device.collectDevice(id)
        console.log('收藏设备响应:', res)
        
        // 收藏成功后刷新收藏列表
        if (res.code === 200) {
          // 更新公共设备列表中的收藏状态
          const publicDevice = this.publicDevices.find(d => d.id === id)
          if (publicDevice) {
            publicDevice.isCollected = true
            publicDevice.collected = true
          }
          
          const collectedRes = await this.loadCollectedDevices()
          console.log('刷新收藏列表结果:', collectedRes)
        }
        return res
      } catch (error) {
        console.error('收藏设备失败:', error)
        throw error
      }
    },
    
    // 取消收藏
    async uncollectDevice(id) {
      try {
        console.log('开始取消收藏设备:', id)
        const res = await api.device.uncollectDevice(id)
        console.log('取消收藏设备响应:', res)
        
        // 取消收藏成功后刷新收藏列表并更新公共设备列表中的收藏状态
        if (res.code === 200) {
          // 更新公共设备列表中的收藏状态
          const publicDevice = this.publicDevices.find(d => d.id === id)
          if (publicDevice) {
            publicDevice.isCollected = false
            publicDevice.collected = false
          }
          
          // 从收藏列表中移除
          this.collectedDevices = this.collectedDevices.filter(d => d.id !== id)
          
          // 刷新收藏列表
          await this.loadCollectedDevices()
        }
        return res
      } catch (error) {
        console.error('取消收藏设备失败:', error)
        throw error
      }
    },
    
    // 切换收藏状态
    async toggleCollect(id) {
      try {
        console.log('切换收藏状态, 设备ID:', id)
        const device = [
          ...this.privateDevices, 
          ...this.publicDevices
        ].find(d => d.id === id)
        
        if (!device) {
          throw new Error('设备不存在')
        }
        
        // 使用正确的属性名判断
        const isCollected = device.isCollected || device.collected || false
        console.log('当前收藏状态:', isCollected)
        
        let res
        if (isCollected) {
          res = await api.device.uncollectDevice(id)
        } else {
          res = await api.device.collectDevice(id)
        }
        
        // 成功后，更新本地状态，确保正确的属性名
        if (res.code === 200) {
          device.isCollected = !isCollected
          device.collected = !isCollected
          
          console.log('更新后收藏状态:', device.isCollected)
          
          // 更新收藏列表
          await this.loadCollectedDevices()
        }
        
        return res
      } catch (error) {
        console.error('切换收藏失败:', error)
        throw error
      }
    }
  }
})